package com.ning.google;

import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import com.google.gdata.client.analytics.AnalyticsService;
import com.google.gdata.client.analytics.DataQuery;
import com.google.gdata.data.analytics.DataEntry;
import com.google.gdata.data.analytics.DataFeed;
import com.google.gdata.util.AuthenticationException;

public class GAnalyticsAutoManager2 {

	private static final String CLIENT_USERNAME = "zhufukc@gmail.com";
	private static final String CLIENT_PASS = "zhufukc74";
	private static final String TABLE_ID = "ga:47208457";

	private static GAnalyticsAutoManager2 _instance = new GAnalyticsAutoManager2();

	public static GAnalyticsAutoManager2 instance() {
		return _instance;
	}
	
	private final AnalyticsService analyticsService;
	
	public GAnalyticsAutoManager2(){
		analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0");
		try {
			analyticsService.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
	}

	public List<GeneralInfo> getGeneralInfo() {
		List<GeneralInfo> list = new ArrayList<GeneralInfo>();
		try {
			DataQuery query = new DataQuery(new URL("https://www.google.com/analytics/feeds/data"));
			query.setStartDate(getLastWeekDate());
			query.setEndDate(getDate());
			query.setDimensions("ga:date");
			query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:avgTimeOnSite,ga:percentNewVisits");
			query.setSort("-ga:date");
			query.setMaxResults(10);
			query.setIds(TABLE_ID);

			DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),DataFeed.class);

			for (DataEntry entry : dataFeed.getEntries()) {
				GeneralInfo infoone = new GeneralInfo();
				infoone.setAvgtime((int) (Double.parseDouble(entry
						.stringValueOf("ga:avgTimeOnSite"))));
				infoone.setNewuv(Integer.parseInt(entry
						.stringValueOf("ga:newVisits")));
				infoone.setUv(Integer.parseInt(entry
						.stringValueOf("ga:visitors")));
				infoone.setPv(Integer.parseInt(entry
						.stringValueOf("ga:pageviews")));
				infoone.setPercentNewUv(Double.parseDouble(entry
						.stringValueOf("ga:percentNewVisits")));
				infoone.setDate(convertDate(entry.stringValueOf("ga:date")));
				list.add(infoone);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public List<SourceInfo> getSourceInfo(boolean isToday) {

		List<SourceInfo> list = new ArrayList<SourceInfo>();
		try {
			DataQuery query = new DataQuery(new URL(
					"https://www.google.com/analytics/feeds/data"));
			String date = getYesterDayDate();
			if(isToday) date = getDate();
			query.setStartDate(date);
			query.setEndDate(date);
			query.setDimensions("ga:date,ga:source");
			query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:percentNewVisits");
			query.setSort("-ga:pageviews");
			query.setFilters("ga:pageviews>10");
			query.setMaxResults(100);
			query.setSegment("gaid::-8");
			query.setIds(TABLE_ID);

			DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),
					DataFeed.class);

			for (DataEntry entry : dataFeed.getEntries()) {
				SourceInfo infotwo = new SourceInfo();
				infotwo.setUv(Integer.parseInt(entry
						.stringValueOf("ga:visitors")));
				infotwo.setPv(Integer.parseInt(entry
						.stringValueOf("ga:pageviews")));
				infotwo.setDate(convertDate(entry.stringValueOf("ga:date")));
				infotwo.setTitle(entry.stringValueOf("ga:source"));
				infotwo.setNewUv(Integer.parseInt(entry
						.stringValueOf("ga:newVisits")));
				infotwo.setPercentNewUv(Double.parseDouble(entry
						.stringValueOf("ga:percentNewVisits")));
				list.add(infotwo);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public List<SearchInfo> getSearchInfo(boolean isToday) {

		List<SearchInfo> list = new ArrayList<SearchInfo>();
		try {
			DataQuery query = new DataQuery(new URL(
					"https://www.google.com/analytics/feeds/data"));
			String date = getYesterDayDate();
			if(isToday) date = getDate();
			query.setStartDate(date);
			query.setEndDate(date);
			query.setDimensions("ga:date,ga:source");
			query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:percentNewVisits");
			query.setSort("-ga:pageviews");
			query.setFilters("ga:pageviews>10");
			query.setMaxResults(100);
			query.setSegment("gaid::-6");
			query.setIds(TABLE_ID);

			DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),
					DataFeed.class);

			for (DataEntry entry : dataFeed.getEntries()) {
				SearchInfo infotwo = new SearchInfo();
				infotwo.setUv(Integer.parseInt(entry
						.stringValueOf("ga:visitors")));
				infotwo.setPv(Integer.parseInt(entry
						.stringValueOf("ga:pageviews")));
				infotwo.setDate(convertDate(entry.stringValueOf("ga:date")));
				infotwo.setTitle(entry.stringValueOf("ga:source"));
				infotwo.setNewUv(Integer.parseInt(entry
						.stringValueOf("ga:newVisits")));
				infotwo.setPercentNewUv(Double.parseDouble(entry
						.stringValueOf("ga:percentNewVisits")));
				
				list.add(infotwo);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public HashMap<String,GeneralInfo> getAppDetailsInfo(){
		HashMap<String,GeneralInfo> maps = new HashMap<String,GeneralInfo>();
		String[] datas1 = new String[]{"All","WebSelf","QQMail","WebQQ","360Desktop","360SEApp","Tqq","SinAapp","Renren","BaiduApp","TianYaApp","Q+","JiaThis","kaixin001"
				,"picapp","t163","cnfol","newsapp","toolsapp","search","mobile"};
		String[] datas2 = new String[]{"","gaid::1877811261","gaid::1300005415","gaid::960794372","gaid::2112745087","gaid::1818061867","gaid::1309064845","gaid::571678374","gaid::1338240564","gaid::1510974722","gaid::703110469","gaid::1293097597","gaid::63390337","gaid::34381578"
				,"gaid::471702186","gaid::665809246","gaid::1526588065","gaid::2019157341","gaid::529957698","gaid::-6","gaid::-11"};
		for(int i=0;i<datas1.length;i++){
			try {
				DataQuery query = new DataQuery(new URL("https://www.google.com/analytics/feeds/data"));
				String date = getDate();
				query.setStartDate(date);
				query.setEndDate(date);
				query.setMetrics("ga:pageviews,ga:visitors,ga:newVisits,ga:avgTimeOnSite,ga:percentNewVisits,ga:pageviewsPerVisit,ga:visitBounceRate");
				query.setMaxResults(10);
				query.setSegment(datas2[i]);
				query.setIds(TABLE_ID);
				DataFeed dataFeed = analyticsService.getFeed(query.getUrl(),DataFeed.class);
				DataEntry entry = dataFeed.getEntries().get(0);

				GeneralInfo infoone = new GeneralInfo();
				infoone.setAvgtime((int) (Double.parseDouble(entry
						.stringValueOf("ga:avgTimeOnSite"))));
				infoone.setNewuv(Integer.parseInt(entry
						.stringValueOf("ga:newVisits")));
				infoone.setUv(Integer.parseInt(entry
						.stringValueOf("ga:visitors")));
				infoone.setPv(Integer.parseInt(entry
						.stringValueOf("ga:pageviews")));
				infoone.setPercentNewUv(Double.parseDouble(entry
						.stringValueOf("ga:percentNewVisits")));
				infoone.setPerPageUser(Double.parseDouble(entry
						.stringValueOf("ga:pageviewsPerVisit")));
				infoone.setExitRate(Double.parseDouble(entry
						.stringValueOf("ga:visitBounceRate")));
				
				maps.put(datas1[i], infoone);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return maps;
	}
	
	private String getDate() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, -1);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	private String getYesterDayDate() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, -2);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	private String getLastWeekDate() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, -3);
		return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
	}

	private String convertDate(String date) {
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf2.format(sdf1.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
}
